import { PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Divider,
  message,
  DatePicker,
  Radio,
  Select,
  Descriptions,
  Image,
  Upload,
  Input,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UploadImg from '@/components/UploadImg';
import FormItem from 'antd/lib/form/FormItem';
import styles from '../../../global.less';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import {
  queryRule,
  updateRule,
  addRule,
  getMember,
  uploadState,
  storeList,
  exportVip,
} from './service';
import { getDictionary } from './service';
import moment from 'moment';
import { money_trans, saveFileAs, transTitle } from '@/utils/utils';
import defaultSetting from '@/../config/defaultSettings';
import Access from '@/components/Access/Access';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在更新');

  try {
    await updateRule({
      ...fields,
    });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

const { Option } = Select;
const dateFormat = 'YYYY/MM/DD';
const TableList = (props) => {

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateVip, handleUpdateVip] = useState(false);
  const [count, setCount] = useState();
  const [FormValues, setFormValues] = useState({});
  const [facePicture, setFacePicture] = useState();
  const [cityState, setCityState] = useState(true);
  const [numberReadOnly, setNumberReadOnly] = useState(false);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [city, setCity] = useState();
  const [province, setProvince] = useState();
  const [area, setArea] = useState([]);
  const [areaState, setAreaState] = useState(true);
  const [must, setMust] = useState(true);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [memberState, setMemberState] = useState(false);
  const [memberValue, setMemberValue] = useState({});
  const [storeArray, setStoreArray] = useState([]);
  const uploadOnChange = (info) => {
    setUploadLoading(true);
    if (info.file.status === 'done') {
      setUploadLoading(false);
      const {
        file: {
          response: { code },
        },
      } = info;
      if (code == 0) {
        actionRef.current.reload();
        message.success('导入成功');
      } else {
        message.error('导入失败请重试！');
      }
    } else {
      // message.error('导入失败请重试！');
    }
  };
  const handleMember = (payload) => {
    getMember(payload).then((res) => {
      const { code, data } = res;
      code === 0 ? setMemberValue(data) : message.error('错误！');
    });
  };
  const handleSetFacePicture = (payload) => {
    setFacePicture(payload.url);
  };
  // 选择获取市
  const handleProvince = async (value) => {
    if (
      value === '1372759026386952193' ||
      value === '1372759018577158146' ||
      value === '1372759017524387842'
    ) {
      setMust(false);
    } else {
      setMust(true);
    }
    await getDictionary('city', value).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setCityState(false);
        setCity(data);
      }
    });
  };
  // 选择获取省
  const handleCity = async (value) => {
    await getDictionary('area', value).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setAreaState(false);
        setArea(data);
      }
    });
  };

  const getProvince = async () => {
    await getDictionary('province').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setProvince(data);
      }
    });
    await getDictionary('city').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setCity(data);
      }
    });
    await getDictionary('area').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setArea(data);
      }
    });
  };
  const getStore = () => {
    storeList()
      .then((res) => {
        const { code } = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleOutVip = () => {
    setUploadLoading(true);
    exportVip().then((res) => {
      if (res) {
        setUploadLoading(false);
        if (res.type === 'application/json'){
          res.text().then(res=>{
            message.error(JSON.parse(res).message);
          })
        }else{
          saveFileAs(res, '会员');
        }
      }
    });
  };
  useEffect(() => {
    getProvince();
    getStore();
  }, []);
  const handleState = (params) => {
    params.status === 1 ? (params.status = 0) : (params.status = 1);
    uploadState(params).then((res) => {
      const { code } = res;
      code === 0 ? actionRef.current.reload() : null;
    });
  };
  const columns = [
    {
      title: '会员卡号',
      dataIndex: 'number',
      valueType: 'text',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input disabled={numberReadOnly} />;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '会员卡号为必填项',
          },
        ],
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '姓名为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a onClick={() => setRow(entity)}>{dom}</a>;
      },
    },

    {
      title: '手机号',
      dataIndex: 'mobile',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '手机号为必填项',
          },
        ],
      },
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: false,
            message: '身份证号为必填项',
          },
          {
            pattern: /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/,
            message: '请输入正确的身份证号',
          },
        ],
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      hideInSearch: true,
      render: (dom) => {
        return <span>{dom === 0 ? '女' : (dom===1?'男':'未知')}</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Radio.Group>
            <Radio value={1}>男</Radio>
            <Radio value={0}>女</Radio>
            <Radio value={2}>未知</Radio>
          </Radio.Group>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '性别为必选项',
          },
        ],
      },
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      valueType: 'text',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <span>{record.birthday ? new Date(record.birthday).toLocaleDateString() : null}</span>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <DatePicker format={dateFormat} style={{ width: '100%' }} />;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Processing',
        },
        1: {
          text: '禁用',
          status: 'error',
        },
      },
    },
    {
      title: '所在省',
      dataIndex: 'provinceId',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在省" onSelect={handleProvince}>
            {province?province.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            }):null}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: false,
            message: '所在省为必填项',
          },
        ],
      },
    },
    {
      title: '所在市',
      dataIndex: 'cityId',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: !must,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在市" disabled={cityState} onSelect={handleCity}>
            {city?city.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            }):null}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: false,
            message: '所在市为必填项',
          },
        ],
      },
    },
    {
      title: '所在区县',
      dataIndex: 'areaId',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: !must,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在区县" disabled={areaState}>
            {area?area.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            }):null}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: false,
            message: '所在区县为必填项',
          },
        ],
      },
    },
    {
      title: '地址',
      dataIndex: 'address',
      hideInSearch: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      hideInSearch: true,
      hideInTable:true,
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: '邮箱格式不正确',
          },
        ],
      },
    },

    {
      title: '头像',
      dataIndex: 'icon',
      hideInSearch: true,
      hideInTable: true,
      render: (_, payload) => {
        return (
          <>
            {' '}
            <Image className={styles.img_div} src={_} />{' '}
          </>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {FormValues ? (
              <FormItem name="icon" className="formItem_div">
                <UploadImg
                  imgUrl={facePicture}
                  showImgUrl={facePicture}
                  subpath="icon"
                  handleSetFacePicture={handleSetFacePicture}
                />
              </FormItem>
            ) : (
              <FormItem name="icon" className="formItem_div">
                <UploadImg subpath="icon" handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },

    {
      title: '销售姓名',
      hideInSearch: true,
      dataIndex: 'salesName',
    },
    {
      title: '开卡店铺',
      hideInSearch: true,
      dataIndex: 'storeName',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择开卡店铺"
            showSearch
            allowClear
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {storeArray.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '开卡店铺',
      dataIndex: 'pcStoreId',
      hideInTable: true,
      hideInForm:true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择开卡店铺"
            showSearch
            allowClear
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {storeArray.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <Access accessKey={"@updateMember"}>
              <a
                onClick={() => {
                  let list = JSON.parse(JSON.stringify(record));
                  list.birthday = record.birthday ? moment(record.birthday) : '';
                  setFacePicture(record.icon);
                  handleUpdateVip(true);
                  setStepFormValues(list);
                  handleModalVisible(true);
                  setNumberReadOnly(false);
                  setAreaState(true);
                  setCityState(true);
                }}
              >
                修改
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@seeMember"}>
              <a
                onClick={() => {
                  handleMember(record.id);
                  setMemberState(true);
                }}
              >
                查看
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@disableMember"}>
              <a
                onClick={() => {
                  handleState(record);
                }}
              >
                {record.status == '1' ? '启用' : '禁用'}
              </a>
              <Divider type="vertical" />
            </Access>
            <a
              onClick={() => {
                props.history.replace({
                  pathname: '/OrderManagement/StoreOrder',
                  query: {
                    cardNum: record.number,
                    type: 2,
                  },
                });
              }}
            >
              充值记录
            </a>
            <Divider type="vertical" />

            <a
              onClick={() => {
                props.history.replace({
                  pathname: '/OrderManagement/StoreOrder',
                  query: {
                    cardNum: record.number,
                    type: 1,
                  },
                });
              }}
            >
              消费记录
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                props.history.push({
                  pathname: '/VipManagement/PointsManagement',
                  query: {
                    memberNumber: record.number,
                  },
                });
              }}
            >
              积分记录
            </a>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="会员列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: 1200 }}
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@newMember"}>
            <Button
              type="primary"
              onClick={() => {
                handleUpdateVip(false);
                handleModalVisible(true);
                setFacePicture();
                setNumberReadOnly(false);
              }}
            >
              <PlusOutlined /> 新建会员
            </Button>
          </Access>
          ,
          <Access accessKey={"@uploadMember"}>
            <Upload
              name="file"
              action={() => {
                return `${defaultSetting.baseUrl}member/old/excel`;
              }}
              listType="picture"
              showUploadList={false}
              maxCount={1}
              onChange={uploadOnChange}
              headers={{ token: sessionStorage.getItem('token'), type: 'ADMIN' }}
            >
              <Button type="primary" loading={uploadLoading} icon={<DownloadOutlined />}>
                导入会员数据
              </Button>
            </Upload>
          </Access>
          ,
          <Access accessKey={"@downloadMember"}>
            <Button danger onClick={handleOutVip} loading={uploadLoading} icon={<UploadOutlined />}>
              导出会员数据
            </Button>
          </Access>
          ,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      <CreateForm
        width={800}
        title={updateVip ? '修改会员信息' : '新建会员'}
        onCancel={() => {
          setMust(true);
          handleUpdateVip(false);
          setNumberReadOnly(false);
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            let newForm = JSON.parse(JSON.stringify(stepFormValues));
            if (
              value.provinceId != newForm.provinceId &&
              (value.cityId == newForm.cityId || value.areaId == newForm.areaId)
            ) {
              message.warning('请正确选择所在市或所在区');
            } else {
              if (value.birthday) {
                value.birthday = Date.parse(value.birthday.substring(0, 10));
              }
              value.icon = facePicture;
              updateVip === true ? (value.id = stepFormValues.id) : (value.register = 1);
              if (updateVip === true){
                updateRule({
                  ...value,
                }).then(res=>{
                  handleModalVisible(false);
                  setMust(true);
                  if (res && res.code === 0){
                    message.success('修改成功');
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  }
                });
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: updateVip === true ? stepFormValues : '',
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        width={800}
        onCancel={() => {
          setMemberState(false);
        }}
        modalVisible={memberState}
      >
        <div>
          <Divider orientation="left">账户信息</Divider>
          <Descriptions>
            {
              (memberValue && memberValue.flag) ?  <Descriptions.Item label="余额">

              {memberValue ? money_trans(memberValue.balance, true) : '暂无'}
              </Descriptions.Item> : <Descriptions.Item label="跨店余额">

                {memberValue ? money_trans(memberValue.hideBalance, true) : '暂无'}
              </Descriptions.Item>
            }

            <Descriptions.Item label="银行名称">
              {memberValue ? memberValue.bankName : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="银行卡号">
              {memberValue ? memberValue.bankNumber : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="积分">
              {memberValue ? memberValue.integral : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="冻结余额">
              {memberValue ? money_trans(memberValue.frozenAmount, true) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="冻结积分">
              {memberValue ? memberValue.frozenIntegral : '暂无'}
            </Descriptions.Item>
          </Descriptions>
        </div>
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
